import { FAQList, questionList } from "../../api/ask";
import { classList } from "../../api/class";
import { drivingSchoolByCity } from "../../api/drivingSchool";
import { SitePageProps, trainSiteList } from "../../api/site";
import { regionList, reverseGeocoder } from "../../api/system";
import { openServer, shareAppMessageSet } from "../../utils/config";
import { dataCollection } from "../../utils/dataCollection";
import { listProps } from "../../utils/type";
import { isMunicipality } from "../../utils/util";
import {
  bannerProps,
  drivingSchoolItemMsg,
  classifyTabItemProps,
} from "./config";

var app = getApp();

interface siteProps extends listProps {
  lat: number; //纬度
  lng: number; //经度
  regionId: string; //区id
  schoolId: string; //驾校id
}

interface currentDrivingSchoolProps {
  name: string;
  qualification: string;
  city: string;
  id: string;
}

interface siteType {
  regionName: string;
  regionId: string;
  list: any[];
}

type DataProps = {
  selectTypeIndex: number;
  popupVisibe: boolean; //弹窗是否显示
  scrollTop: number; //页面滚动距离顶部距离
  classifytabIconList: classifyTabItemProps[];
  drivingSchoolLogo: string;
  drivingSchoolLogoWidth: number; //驾校logo width
  drivingSchoolLogoHeight: number; //驾校logo height
  classData: listProps; //班别列表数据
  cityDrivingSchool: any[]; //所有城市
  currentCity: string; //当前城市
  currentDrivingSchool: currentDrivingSchoolProps;
  siteData: siteProps; //场地列表数据
  drivingSchoolId: string; //
  userLocation: string; //用户位置
  questionData: listProps; //问大家数据
  loginStatus: boolean; //登录状态
  regionArray: any[]; //当前城市下的区
  regionIds: string[]; //当前城市下的区id
  regionIndex: number; //当前城市选中在的区下标
  refuseLocation: boolean; //用户拒绝授权
  roll: any[]; //轮播数据
  avatar: string; // 用户头像
  signUpPlayState: boolean; // 轮播是否自动播放
  interval: number; //轮播滚动间隔时长
  swiperData: any[]; //轮播内容
  scrollViewRefresherTriggered: boolean; //下拉刷新状态
  scrollViewRefresherEnabled: boolean; //数据区域下拉刷新 默认允许下拉 当页面向下滑动禁止下拉刷新功能
  quizBtnVsible: boolean;
  userInitialCity: string; //用户初始城市
  userChangeCity: boolean; //用户是否切换了城市
  refresherTriggered: boolean;
  classNumber: string[]; //当前驾校存在的版本
  loadingVisible: boolean;
  FAQList: any[]; //常见问题列表
  pageReady: boolean; //页面是否准备好
  isScroll: boolean; //页面是否在滑动
  translate3d: string;
  theme: string;
  consultVisible: boolean; //控制悬浮客服按钮出现
  banner: bannerProps; //宣传图
  themeCode: string; //城市编码
  refresherBackground: string; //刷新页面背景色
  navigationBackground: string; //导航背景色
  drivingSchoolMsg: drivingSchoolItemMsg; //展示的驾校logo，昵称
  headPortrait: string; //导航默认的头像
  siteAllData: siteType[];
  navigatorBarHeight: 0; //导航的高度
  nearestSite: any[]; //最近场地数据信息
  bottomLoadingActive: boolean; //底部加载是否触发
  scrolling: boolean; //是否在滚动
  scrollingAsk: boolean; //是否在滚动，针对我要提问按钮
};

Page({
  data: <DataProps>{
    themeCode: "",
    banner: {
      url: "",
      height: 0,
    },
    refresherBackground: "",
    navigationBackground: "",
    consultVisible: false,
    theme: "dark",
    translate3d: "0px,0px,0px",
    isScroll: false,
    pageReady: false,
    FAQList: [],
    loadingVisible: true,
    classNumber: [],
    refresherTriggered: false,
    userChangeCity: false,
    userInitialCity: "",
    quizBtnVsible: false,
    scrollViewRefresherTriggered: false,
    scrollViewRefresherEnabled: true,
    signUpPlayState: false,
    interval: 5000,
    scrollTop: 0,
    selectTypeIndex: 0, //选择类型展示的下标
    drivingSchoolLogoWidth: 0,
    drivingSchoolLogoHeight: 0,
    classifytabIconList: [],
    popupVisibe: false,
    regionIndex: 0,
    regionArray: [],
    regionIds: [],
    classData: {
      current: 1,
      total: 0,
      loading: false,
      list: [],
    },
    currentDrivingSchool: {
      city: "",
      name: "",
      qualification: "",
      id: "",
    },
    cityDrivingSchool: [],
    drivingSchoolId: "",
    siteData: {
      current: 1,
      total: 0,
      lat: 0,
      lng: 0,
      schoolId: "",
      regionId: "",
      list: [],
      loading: false,
    },
    userLocation: "",
    questionData: {
      current: 1,
      total: 0,
      list: [],
      loading: false,
    },
    loginStatus: false,
    currentCity: "",
    refuseLocation: false,
    roll: [],
    avatar: "",
    swiperData: [1, 2, 3, 4],
    drivingSchoolLogo: "",
    drivingSchoolMsg: {
      logo: "",
      backgroundColor: "",
      identifyIcon: "",
      moreIcon: "",
      color: "",
    },
    headPortrait: "",
    siteAllData: [],
    navigatorBarHeight: 0,
    nearestSite: [],
    bottomLoadingActive: false,
    scrolling: false,
    scrollingAsk: false,
  },
  onLoad: function (options: any) {
    wx.setStorageSync("channel", options.channel);
    this.getUserLocation();

    const userInfo = wx.getStorageSync("userInfo");
    this.setData({
      loginStatus: wx.getStorageSync("loginStatus"),
      avatar: userInfo?.avatar,
    });

    //获取appbar实例
    if (typeof this.getAppBar === "function") {
      app.globalData.appBarComp = this.getAppBar();
      console.log("app.globalData.appBarComp", app.globalData.appBarComp);
    }
  },
  onHide() {
    this.setData({
      signUpPlayState: false,
      swiperData: [],
    });
    //记录离开当前页面
    dataCollection.setPageMapData("leave");
  },
  onUnload() {
    //记录离开当前页面
    dataCollection.setPageMapData("leave");
  },
  onShow() {
    const userInfo = wx.getStorageSync("userInfo");
    const loginStatus = wx.getStorageSync("loginStatus");
    this.setData({
      loginStatus,
      avatar: userInfo?.avatar,
      signUpPlayState: true,
      swiperData: [1, 2, 3],
    });
    console.log("loginStatus", loginStatus, userInfo);
    //如果用户拒绝了地理位置的授权
    if (this.data.refuseLocation) {
      wx.getSetting({
        success: (e: any) => {
          console.log("getSetting", e);
          if (e.authSetting["scope.userLocation"]) {
            wx.authorize({
              scope: "scope.userLocation",
              success: (res: any) => {
                // 用户已经同意小程序使用获取地理位置
                console.log("用户已经同意小程序使用获取地理位置", res);
                this.data.nearestSite.length = 0;
                this.data.siteAllData.length = 0;

                // const ids: string[] = [];
                // this.data.regionIds.length = 0;
                // this.data.regionArray.forEach((item) => {
                //   ids.push(item.id);
                // });

                this.setData({
                  "siteData.current": 1,
                  "classData.current": 1,
                });
                this.getUserLocation(() => {
                  //重新拉取场地
                  console.log("重新拉取场地");
                  this.getTrainSiteList();
                });
              },
            });
          }
        },
      });
    }

    //记录进入当前页面次数
    dataCollection.setPageMapData("enter", "首页");
  },
  onReady() {
    const query = wx.createSelectorQuery();
    query.select("#navigatorBar").boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec((res) => {
      console.log("navaigator", res);
      this.setData({
        navigatorBarHeight: res[0].height,
      });
    });
  },
  //获取地理坐标
  getUserLocation(callback = () => {}) {
    //获取当前的模糊地理位置
    wx.getLocation({
      altitude: true,
      isHighAccuracy: true,
      success: (res: any) => {
        console.log("getLocation success", res);
        // wx.setStorageSync('coords', { latitude: res.latitude, longitude: res.longitude })
        //29.612835,经度106.58042
        const latitude = res.latitude;
        const longitude = res.longitude;
        reverseGeocoder(latitude, longitude).then((e) => {
          this.getCurrentCityByLoaction(
            e.result.regionId,
            latitude,
            longitude,
            e.result.address,
            e.result.regionName,
            callback
          );
        });
        this.setData({
          refuseLocation: false,
        });
      },
      fail: (res: any) => {
        console.log("getLocation fail", res);
        this.setData({
          refuseLocation: true,
        });
        //拒绝授权 默认查询深圳
        this.getCurrentCityByLoaction(
          "440303",
          22.543687,
          114.059625,
          "",
          "",
          callback
        );
      },
    });
  },
  //通过坐标获取当前城市
  getCurrentCityByLoaction(
    regionId: string,
    latitude: number,
    longitude: number,
    address: string,
    regionName: string,
    callback = () => {}
  ) {
    //保存用户坐标
    wx.setStorageSync("coords", { latitude, longitude });
    app.globalData.coords = {
      lng: longitude,
      lat: latitude,
    };

    //根据返回的 regionId 判断当前城市
    const cityRegion: any[] = [];

    //通过regionid 获取城市区行政
    let cityId = isMunicipality(regionId)
      ? regionId.slice(0, 2) + "0000"
      : regionId.slice(0, 4) + "00";
    // console.log('cityId', cityId)

    regionList(cityId).then((res) => {
      cityRegion.push(...res.result);
      console.log("城市区行政", cityRegion);
      let selectRegionIndex = 0;

      app.globalData.regionMap.clear();

      this.data.regionIds.length = 0;
      const ids: string[] = [];

      cityRegion.forEach((item: any, index: number) => {
        if (Number(item.id) === Number(regionId)) {
          selectRegionIndex = index;
        }
        if (index === 0 && cityRegion.length === 1) {
          //判断类似像东莞这种城市，没有区，默认使用城市id
          item.id = regionId;
        }
        ids.push(item.id);
        app.globalData.regionMap.set(item.id, item.fullname);
      });

      wx.setStorageSync("userLocation", address);

      //用户没有授权，默认是深圳市
      let rName = regionName.split(",");
      const cityName = rName[2] || "深圳市";
      app.globalData.currentCity = cityName;
      // console.log('当前城市', cityName)

      //记录访问的城市
      dataCollection.setMapData("city", cityName);
      //记录访问的城市区
      dataCollection.setMapData(
        "region",
        cityRegion[selectRegionIndex].fullname
      );

      wx.setStorageSync(
        "userInitialCity",
        regionName ? rName[1] + "-" + rName[2] : cityName
      );

      this.setData({
        userLocation: address,
        "siteData.lng": longitude,
        "siteData.lat": latitude,
        "siteData.regionId": regionId,
        currentCity: cityName,
        userInitialCity: cityName,
        regionArray: [...cityRegion],
        regionIndex: selectRegionIndex,
        signUpPlayState: true,
        regionIds: [...ids],
      });
      callback();
      this.getDrivingSchool();
    });
  },
  //监听选择的类型下标
  onSelectType(e: any) {
    let index = e.currentTarget.dataset.index;
    if (index === this.data.selectTypeIndex) {
      return;
    }
    this.setData({
      selectTypeIndex: index,
    });
    //用户切换类别后，判断当前类别数据是否加载过 且 当前不是刷新
    if (!this.data.refresherTriggered) {
      if (index === 1 && this.data.siteAllData.length === 0) {
        //场地
        this.getTrainSiteList(() => {
          console.log(this.data.siteAllData.length, this.data.refuseLocation);
          //当切换到场地列表时，加载当前区域后，发现当前区域没有场地，则按照区域列表，加载下一个区域
          // if (
          //   this.data.siteData.list.length === 0 &&
          //   this.data.refuseLocation
          // ) {
          //   let index = this.data.regionIndex;
          //   index++;
          //   let id = this.data.regionArray[index].id;
          //   console.log('regionId',id)
          //   this.setData({
          //     "siteData.current": 1,
          //     "siteData.regionId": id,
          //     regionIndex: index,
          //   });
          //   this.getTrainSiteList(() => {
          //     this.setData({
          //       "siteData.loading": true,
          //     });
          //   });
          // }
        });
      } else if (index === 2 && this.data.questionData.current === 1) {
        //问大家
        this.getQuestion();
      } else if (index === 3 && !this.data.FAQList.length) {
        //客服 默认获取10条
        FAQList(1, 10).then((res) => {
          this.setData({
            FAQList: [...res.result.records],
          });
        });
      }
    }
  },
  //显示选择城市弹窗
  onShowAddrPopup() {
    this.setData({
      popupVisibe: true,
    });
    app.globalData.appBarComp &&
      app.globalData.appBarComp.setData({
        scrolling:true,
      });
  },
  //监听选择城市弹窗显示隐藏
  onPopupVsible(e: any) {
    console.log(e, this.data.currentCity, this.data.userInitialCity);
    app.globalData.appBarComp &&
    app.globalData.appBarComp.setData({
      scrolling:false,
    });
    //弹窗关闭判断用户选择的城市和当前展示的城市是否一致
    if (e.detail.city === this.data.currentCity) {
      this.setData({
        popupVisibe: e.detail.visible,
      });
    } else {
      this.setData({
        pageReady: false,
        selectTypeIndex: 0,
        "classData.loading": false,
        "siteData.loading": false,
        "questionData.loading": false,
        popupVisibe: e.detail.visible,
      });

      this.getRegionListByCityId(e.detail.cityId, (list: any[]) => {
        this.data.regionIds.length = 0;
        this.data.siteAllData.length = 0;
        this.setData({
          currentCity: e.detail.city,
          userChangeCity:
            e.detail.city === this.data.userInitialCity ? false : true,
          "classData.list": [],
          "classData.current": 1,
          "questionData.list": [],
          "questionData.current": 1,
          "siteData.list": [],
          "siteData.current": 1,
          "siteData.regionId": list[0].id, //选择城市后，默认选择第一个区
          regionArray: [...list],
          regionIndex: 0,
        });
        console.log("regionArray", list);
        //记录访问的城市
        dataCollection.setMapData("city", e.detail.city);
        this.getDataByCity();
      });
    }
  },
  //通过市id获取行政区域列表
  getRegionListByCityId(cityId: string, callback = (arg: any[]) => {}) {
    let idArray = cityId.split("/");
    //如果是直辖市，则不显示城市，显示直辖市的名称
    let id = idArray[1];
    id = isMunicipality(idArray[0] + "") ? idArray[0] : idArray[1];

    console.log("city id", id);
    regionList(id).then((res) => {
      const list: any = [];
      app.globalData.regionMap.clear();
      res.result.forEach((item: any, index: number) => {
        if (index === 0 && res.result.length === 1) {
          //判断类似像东莞这种城市，没有区，默认使用城市id
          item.id = cityId.split("/")[1] + "00";
        }
        console.log(item);
        app.globalData.regionMap.set(item.id, item.fullname);
        list.push(item);
      });
      console.log("app.globalData.regionMap", app.globalData.regionMap);
      callback(list);
    });
  },
  n: 0,
  //监听图片加载完成
  onImageLoad(res: any) {
    let w = res.detail.width > 190 ? 190 : res.detail.width;
    let h = (res.detail.height * w) / res.detail.width;
    //控制logo的高度在100rpx
    if (h > 100) {
      w = (w * 100) / h;
      h = 100;
    }
    this.setData({
      drivingSchoolLogoWidth: w,
      drivingSchoolLogoHeight: h,
    });
  },
  //监听banner图加载
  onBannerImageLoad(res: any) {
    console.log("res.detail", res.detail.height);
    this.setData({
      "banner.height": res.detail.height,
    });
  },
  //打开个人页面
  onOpenPageZoom: (res: any) => {
    wx.navigateTo({
      url: res.currentTarget.dataset.path,
      routeType: "wx://zoom",
    });
  },
  //打开页面
  onOpenPage: (res: any) => {
    wx.navigateTo({ url: res.currentTarget.dataset.path });
  },
  //监听选择区域
  onPickerRegionChange(e: any) {
    this.setData({
      regionIndex: e.detail.value,
      "siteData.regionId": this.data.regionArray[e.detail.value].id,
      "siteData.current": 1,
    });
    this.getTrainSiteList();
    //记录访问的城市区
    dataCollection.setMapData(
      "region",
      this.data.regionArray[e.detail.value].fullname
    );
    console.log("region", this.data.regionArray[e.detail.value]);
  },
  //获取班别数据
  getClassListData(callback = () => {}) {
    classList(this.data.classData.current, this.data.siteData.schoolId).then(
      (res: any) => {
        // console.log('班别数据', res.result.records)

        const list: any[] = this.data.classData.list;
        if (this.data.classData.current === 1) {
          list.length = 0;
        }
        list.push(...res.result.records);
        let index = this.data.classData.current;
        index++;
        const obj: listProps = {
          current: index,
          list: [...list],
          total: res.result.total,
          loading: true,
        };

        const map: Map<string, string> = new Map();
        list.forEach((item) => {
          if (!map.has(item.classNumber)) {
            map.set(item.classNumber, item.classNumber);
          }
        });
        // console.log(map)

        const classNum: string[] = [];
        map.forEach((item) => {
          classNum.push(item);
        });
        // console.log('classNum', classNum)
        this.setData({
          classData: obj,
          classNumber: [...classNum],
        });

        //首次进入跳转到登录页
        const isFirst = wx.getStorageSync("first") || "";
        if (!isFirst) {
          wx.setStorageSync("first", new Date().getTime());
          wx.navigateTo({
            url: "/pages/login/login",
          });
        } else {
          //设置客服icon显示
          app.globalData.appBarComp &&
            app.globalData.appBarComp.setData({
              visible: true,
            });
        }

        callback();
      },
      () => {
        callback();
      }
    );
  },
  //获取所有的城市及对应的驾校
  getDrivingSchool() {
    drivingSchoolByCity().then((res) => {
      app.globalData.cityList.length = 0;
      for (const key in res.result) {
        const city = isMunicipality(res.result[key].cityId + "")
          ? key.split("/")[0]
          : key.split("/")[1];
        app.globalData.cityList.push({ city, cityId: res.result[key].cityId });
        app.globalData.cityDrivingSchool.set(city, res.result[key]);
      }

      this.getDataByCity();
    });
  },
  //根据城市获取驾校 | 班别 | 场地
  getDataByCity() {
    //当前区域是否存在驾校
    let isExistDrivingSchool = false;
    //当前城市对应的驾校
    let currDrivingSchool: any;

    //判断map结构数据中是否存在当前城市的学校
    isExistDrivingSchool = app.globalData.cityDrivingSchool.has(
      this.data.currentCity
    );

    // console.log('isExistDrivingSchool：', isExistDrivingSchool, 'current city：', this.data.currentCity)

    if (isExistDrivingSchool) {
      currDrivingSchool = app.globalData.cityDrivingSchool.get(
        this.data.currentCity
      );
      console.log("current city driving school：", currDrivingSchool);
      const styleInfo = currDrivingSchool.styleInfo
        ? JSON.parse(currDrivingSchool.styleInfo)
        : "";
      //获取主题code，没有默认red
      const themeCode = styleInfo.theme ?? "red";
      const theme = app.globalData.theme.get(themeCode);
      for (const key in theme) {
        app.globalData.dictMap.set(key, theme[key]);
      }
      console.log("theme", theme);
      console.log("dictMap", app.globalData.dictMap, themeCode);

      this.setStyleDataByCity(themeCode);

      //设置当前驾校信息
      const currentDrivingSchool: currentDrivingSchoolProps = {
        name: currDrivingSchool.fullName,
        city: this.data.currentCity,
        qualification: currDrivingSchool.qualification,
        id: currDrivingSchool.id,
      };
      //保存到本地
      wx.setStorage({ key: "currentDrivingSchool", data: currDrivingSchool });

      this.setData({
        currentDrivingSchool: currentDrivingSchool,
        "siteData.schoolId": currentDrivingSchool.id,
        drivingSchoolId: currentDrivingSchool.id,
        drivingSchoolLogo: currDrivingSchool.homeLogo,
        "banner.url": styleInfo.homeBanner,
      });

      //获取班别数据
      this.getClassListData(() => {
        this.setData({
          loadingVisible: false,
          pageReady: true,
        });
      });
    } else {
      //当前用户所在区域没有对应的驾校，则默认显示深圳对应的驾校
      const defaultCity = "深圳市";
      this.setData({
        currentCity: defaultCity,
      });
      app.globalData.currentCity = defaultCity;

      //获取深圳市的所有区域
      if (app.globalData.cityDrivingSchool.has(defaultCity)) {
        const cityId = app.globalData.cityDrivingSchool.get(defaultCity).cityId;
        this.getRegionListByCityId(cityId, (list: any[]) => {
          this.setData({
            "siteData.regionId": list[0].id, //选择城市后，默认选择第一个区
            regionArray: [...list],
            regionIndex: 0,
          });
        });
        //重新调用该方法
        this.getDataByCity();
      } else {
        this.setData({
          loadingVisible: false,
          pageReady: true,
        });
      }
    }
  },
  //根据驾校id 区id 经度 纬度 获取场地
  getTrainSiteList(callback = () => {}) {
    /**
     * 用户授权了，拿到用户所在的区id，如果当前区域列表数量少于3个，则加载以下一个区
     * 如果当前用户所在区域为空，则不传区id，接口分页size传1
     *
     * 如果用户没有授权，则默认获取福田区，最近的默认不展示
     */
    console.log("regionids", this.data.regionIds, this.data.siteData.regionId);
    // this.getSiteByRegionId(this.data.siteData.regionId)

    //从已加载的数据中看哪些区已经被加载了
    if (this.data.regionIds.length) {
      let id =
        this.data.siteAllData.length === 0
          ? this.data.siteData.regionId
          : this.data.regionIds[0];
      this.getSiteByRegionId(id).then(
        (res: siteType) => {
          //判断返回的接口是否存在场地列表，不存在则拉取下一个区场地列表
          const newIds = this.data.regionIds.filter((item: string) => {
            return Number(item) !== Number(id);
          });

          const oldArr = this.data.siteAllData;

          console.log(!this.data.refuseLocation, this.data.siteAllData.length);
          if (
            !this.data.refuseLocation &&
            res.list.length &&
            this.data.nearestSite.length === 0
          ) {
            //如果用户授权了地理位置
            this.setData({
              nearestSite: [res.list[0]],
            });
            res.list.shift();
            console.log(
              "nearestSite",
              [res.list[0]],
              res.list,
              "siteAllData",
              this.data.siteAllData
            );
          }
          oldArr.push(res);
          this.setData({
            regionIds: newIds,
            siteAllData: [...oldArr],
          });

          if (res.list.length === 0) {
            this.getTrainSiteList(callback);
          } else if (
            res.list.length <= 3 &&
            this.data.siteAllData.length === 1
          ) {
            //加载的第一个区域，且区场地列表小于等于3，再次加载下一个区
            this.getTrainSiteList(callback);
          }
          callback();
          console.log(this.data.siteAllData);
        },
        () => {
          callback();
        }
      );
    }
  },

  getSiteByRegionId(regionId: string) {
    return new Promise<siteType>((resolve, reject) => {
      const params: SitePageProps = {
        current: this.data.siteData.current,
        lat: this.data.siteData.lat,
        lng: this.data.siteData.lng,
        regionId: regionId,
        schoolId: this.data.siteData.schoolId,
        size: 100,
      };
      trainSiteList(params).then(
        (res) => {
          resolve({
            regionName: app.globalData.regionMap.get(regionId),
            regionId: regionId,
            list: [...res.result.records],
          });
        },
        () => {
          reject();
        }
      );
    });
  },

  getAllSite() {
    const params: SitePageProps = {
      current: this.data.siteData.current,
      lat: this.data.siteData.lat,
      lng: this.data.siteData.lng,
      regionId: this.data.siteData.regionId,
      schoolId: this.data.siteData.schoolId,
      size: 100,
    };

    this.data.siteAllData.length = 0;
    this.data.nearestSite.length = 0;

    const arrFn: any[] = [];

    this.data.regionArray.forEach((item: any) => {
      console.log(item);
      params.regionId = item.id;
      const p = new Promise((resolve) => {
        trainSiteList(params).then(
          (res) => {
            resolve({
              regionName: app.globalData.regionMap.get(item.id),
              regionId: item.id,
              list: [...res.result.records],
            });
          },
          () => {}
        );
      });
      arrFn.push(p);
    });

    Promise.all(arrFn).then((res) => {
      console.log(res);
      const results: any[] = [];
      res.forEach((item: any) => {
        if (item.list.length) {
          results.push(item);
        }
      });
      this.setData({
        nearestSite: [results[0].list[0]],
        siteAllData: [...results],
      });
    });
  },
  //获取问大家问题列表
  getQuestion(callback = () => {}) {
    questionList(
      this.data.questionData.current,
      this.data.siteData.schoolId
    ).then(
      (res) => {
        const list: any[] = this.data.questionData.list;
        if (this.data.questionData.current === 1) {
          list.length = 0;
        }
        list.push(...res.result.records);
        let index = this.data.questionData.current;
        index++;
        const obj: listProps = {
          current: index,
          list: [...list],
          total: res.result.total,
          loading: true,
        };
        this.setData({
          questionData: obj,
        });
        console.log("questionData", obj);
        callback();
      },
      () => {
        callback();
      }
    );
  },
  bindrefresherpulling(res: any) {
    // console.log('bindrefresherpulling', res)
  },
  bindrefresherrefresh(res: any) {
    // console.log('bindrefresherrefresh', res)
    this.setData({
      refresherTriggered: true,
    });
    if (this.data.selectTypeIndex === 0 && this.data.siteData.schoolId) {
      this.setData({
        "classData.current": 1,
      });
      this.getClassListData(() => {
        this.setData({
          refresherTriggered: false,
        });
      });
    } else if (this.data.selectTypeIndex === 1 && this.data.siteData.schoolId) {
      // this.setData({
      //   "siteData.current": 1,
      // });
      // this.getTrainSiteList(() => {
      //   this.setData({
      //     refresherTriggered: false,
      //   });
      // });
    } else if (this.data.selectTypeIndex === 2 && this.data.siteData.schoolId) {
      this.setData({
        "questionData.current": 1,
      });
      this.getQuestion(() => {
        this.setData({
          refresherTriggered: false,
        });
      });
    }
  },
  bindrefresherrestore(res: any) {
    // console.log('bindrefresherrestore', res)
  },
  bindrefresherabort(res: any) {
    // console.log('bindrefresherabort', res)
  },
  startLoad: false,
  bindscrolltolower(res: any) {
    console.log("bindscrolltolower", res);
    if (!this.startLoad) {
      this.startLoad = true;

      if (this.data.selectTypeIndex === 0) {
        console.log("class load");
        if (
          this.data.classData.list.length < Number(this.data.classData.total)
        ) {
          this.getClassListData(() => {
            this.startLoad = false;
          });
        } else {
          this.startLoad = false;
        }
      } else if (this.data.selectTypeIndex === 1) {
        console.log(
          "site load",
          this.data.siteAllData.length,
          this.data.regionArray.length
        );
        if (this.data.siteAllData.length < this.data.regionArray.length) {
          if (!this.data.bottomLoadingActive) {
            this.setData({
              bottomLoadingActive: false,
            });
          }
          this.getTrainSiteList(() => {
            this.setData({
              bottomLoadingActive: false,
            });
            this.startLoad = false;
          });
        } else {
          this.startLoad = false;
        }
      } else if (this.data.selectTypeIndex === 2) {
        console.log("ask load");
        if (
          this.data.questionData.list.length <
          Number(this.data.questionData.total)
        ) {
          this.getQuestion(() => {
            this.startLoad = false;
          });
        } else {
          this.startLoad = false;
        }
      }
    }
  },
  bindscroll(res: any) {
    // console.log("bindscroll", res);
    if (parseInt(res.detail.scrollTop) < 50 && this.n === 0) {
      this.setData({
        scrollTop: parseInt(res.scrollTop) * 2,
      });
    }
    if (Number(res.detail.scrollTop) > 50 && this.n === 0) {
      this.n = 1;
      this.setData({
        scrollTop: 100,
      });
    } else if (Number(res.detail.scrollTop) < 10 && this.n === 1) {
      this.n = 0;
      this.setData({
        scrollTop: 0,
      });
    }
  },
  scrollTimer: 0,
  onScrollStart(res: any) {
    if (this.scrollTimer) {
      clearTimeout(this.scrollTimer);
    }
    if (!this.data.scrolling) {
      this.setData({
        scrolling: true,
        scrollingAsk: this.data.selectTypeIndex === 2 ? true : false,
      });

      app.globalData.appBarComp &&
        app.globalData.appBarComp.setData({
          scrolling: true,
        });
    }

    console.log("onScrollStart", this.data.scrolling);
  },
  onScrollEnd(res: any) {
    this.scrollTimer = setTimeout(() => {
      this.setData({ scrolling: false, scrollingAsk: false });
      app.globalData.appBarComp &&
        app.globalData.appBarComp.setData({
          scrolling: false,
        });
      clearTimeout(this.scrollTimer);
      console.log("onScrollEnd", this.data.scrolling);
    }, 1000);
  },
  //用户点击我要提问按钮，判断用户是否登录
  onClickBtn(res: any) {
    if (this.data.selectTypeIndex === 2) {
      if (this.data.loginStatus) {
        wx.navigateTo({ url: res.currentTarget.dataset.path });
      } else {
        wx.showModal({
          title: "请先登录再操作",
          success: (e: any) => {
            if (e.confirm) {
              wx.navigateTo({ url: "/pages/login/login" });
            } else if (e.cancel) {
              console.log("用户点击取消");
            }
          },
        });
      }
    } else if (this.data.selectTypeIndex === 3) openServer();
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return { ...shareAppMessageSet() };
  },
  //根据城市编码显示对应的数据
  setStyleDataByCity(themeCode: string) {
    this.setData({
      themeCode,
      refresherBackground: app.globalData.dictMap.get(
        "refresherBackgroundColor"
      ),
      navigationBackground: app.globalData.dictMap.get(
        "navigationBackgroundColor"
      ),
      drivingSchoolMsg: app.globalData.dictMap.get("drivingSchoolMessage"),
      classifytabIconList: app.globalData.dictMap.get("homeClassifyTab"),
      headPortrait: app.globalData.dictMap.get("homeHeadPortrait"),
    });

    app.globalData.appBarComp &&
      app.globalData.appBarComp.setData({
        themeCode,
      });

    wx.setStorageSync("themeCode", themeCode);
  },
});
